var app = angular.module("app", ["chart.js"])
    // Optional configuration
    .config(['ChartJsProvider', function (ChartJsProvider) {
        // Configure all charts
        ChartJsProvider.setOptions({
            chartColors: ['#FF5252', '#FF8A80'],
            responsive: false
        });
        // Configure all line charts
        ChartJsProvider.setOptions('line', {
            showLines: true
        });
    }])
    .controller("LineCtrl", ['$scope', '$timeout', '$http', '$location', function ($scope, $timeout, $http, $location) {
        $scope.voiceContent = '';

        // 发送网络请求
        $scope.sendRequest = function (word) {
            var resendUrl = "https://www.samandqq.top:8001/analyse?word="+word;
            var param = '';
            // param += "word=" + word;

            $http.post(resendUrl, param)
                .then(function(response) {
                    $scope.showtip = true;
                    console.log(response);
                    if (response.data.meta.success && response.data.data){
                        console.log(response.data);
                        $scope.factorys = response.data.data;
                    }else {
                        $scope.factorys = [];
                    }
                }, function () {
                    $scope.factorys = [];
                });
        };

        $scope.factorys = [];

        $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
        $scope.series = ['Series A', 'Series B'];
        $scope.data = [
            [65, 59, 80, 81, 56, 55, 40],
            [28, 48, 40, 19, 86, 27, 90]
        ];

        $scope.onClick = function (points, evt) {
            console.log(points, evt);
        };

        $scope.$watch("voiceContent", function (newValue, oldValue) {
            if(oldValue != newValue) {
                console.log($scope.voiceContent);
                if($scope.voiceContent) {
                    $scope.sendRequest($scope.voiceContent);
                }
            }
        }, true);


        $scope.voiceStop = true;
        window.onload = function () {
            const voiceTxt = document.querySelector('#voice-txt');
            const startBtn = document.querySelector('#start-btn');
            const fixedBox = document.querySelector('#fixed-box');
            const fixedTxt = document.querySelector('#fixed-txt');
            const closeBtn = document.querySelector('#close-btn');
            let times = null;

            // 实例化迅飞语音听写（流式版）WebAPI
            const voice = new Voice({

                // 服务接口认证信息 注：apiKey 和 apiSecret 的长度都差不多，请要填错哦，！
                // appId: '5ec244d5',
                // apiSecret: '37912e3e3f205e2a6201ec290452470a',
                // apiKey: '78b6c006f1f3df5e24d315e3dff09212',
                appId: '9a58c360',
                apiSecret: 'MDFmNGUzODMzYzVjYmI5Y2EyMTcxZWE5',
                apiKey: 'f74a343d0ecf1df08a433cf6849b55ce',
                // 注：要获取以上3个参数，请到迅飞开放平台：https://www.xfyun.cn/services/voicedictation 【注：这是我的迅飞语音听写（流式版）每天服务量500（也就是调500次），如果你需求里大请购买服务量：https://www.xfyun.cn/services/voicedictation?target=price】

                onWillStatusChange: function (oldStatus, newStatus) {
                    //可以在这里进行页面中一些交互逻辑处理：注：倒计时（语音听写只有60s）,录音的动画，按钮交互等！
                    fixedBox.style.display = 'block';
                },
                onTextChange: function (text) {
                    //监听识别结果的变化
                    voiceTxt.value = text;
                    fixedTxt.innerText = text;
                    $scope.voiceContent = text;

                    // 1秒钟内没有说话，就自动关闭
                    if (text) {
                        clearTimeout(times);
                        times = setTimeout(() => {
                                this.stop(); // voice.stop();
                        fixedBox.style.display = 'none';
                        $scope.voiceStop = true;
                        $scope.$apply();
                    }, 1000);
                    };
                }
            });

            // 开始识别
            startBtn['onclick'] = function () {
                voice.start();
                $scope.voiceStop = false;
            };

            // 关闭识别
            closeBtn['onclick'] = function () {
                voice.stop();
                fixedBox.style.display = 'none';
                $scope.voiceStop = true;
                $scope.$apply();
            };
        };
    }]);
